'use strict'

const {initORM} = require('psqlorm')
const npargv = require('npargv')

let arg = npargv({
  '@command' : [
      'create', 'show', 'delete'
  ],

  '--name': {
    alias: '-n',
    name: 'name',
    type: 'string'
  },

  '--email': {
    alias: '-e',
    name: 'email',
    type: 'string'
  },

  '--tname': {
    name: 'tname',
    type: 'string'
  },

  '--copy-models': {
    name: 'copyModels',
    type: 'boolean',
    default: false,
    alias: '-cm'
  },

  '--id': {
    name: 'id',
    type: 'string'
  },

  '--force': {
    name: 'force',
    type: 'boolean',
    default: false,
    alias: '-f'
  }
})

let args = arg.args

let dbconfig = {
  port: 5432,
  host: '127.0.0.1',
  max: 2,
  user: 'postgres',
  database: 'dify',
  schema: 'public'
}

let db = initORM(dbconfig)

let uuid = require('./uuid.js')

/**
 *
 * 指定复制的tenants中的空间，需要通过name指定。
 * 复制所有者用户到tenant_account_joins中。
 * 复制volumes中的密钥文件，但是这个过程需要手动完成，创建后仅仅给出命令运行提示。
 *
 * */

;(async () => {
  
  if (arg.command === 'show') {
    let tlist = await db.model('tenants').select()
    for (let t of tlist) {
      console.log(t.name, t.id, t.created_at)
    }
  } else if (arg.command === 'create') {
    //如果指定了名称，则通过名称检查tenant
    let tenant

    if (args.name) {
      tenant = await db.model('tenants').where({name: args.name}).get()
      if (!tenant) {
        console.error('没有找到名称为' + args.name + '的租户')
        return db.end()
      }
    } else {
      //找到最早的租户
      tenant = await db.model('tenants').orderby('created_at', 'asc').get()
    }

    //如果指定了email，则查询是否存在这个用户(accounts)作为拥有者，否则使用默认的owner
    let owner
    let account_id

    if (args.email) {
      owner = await db.model('accounts').where({email: args.email}).get()
      if (!owner) {
        console.error('没有找到用户')
        return db.end()
      }
      account_id = owner.id
    } else {
      let towner = await db.model('tenant_account_joins')
                            .where({tenant_id: tenant.id, role: 'owner'})
                            .get()

      account_id = towner.account_id
    }
    
    //let new_tenant_id = uuid()
    //let new_tenant_joins_id = uuid()
    
    let r = await db.transaction(async (tb, ret) => { 
      let tname = args.tname || (tenant.name + ' Copy')

      let nt = await tb.table('tenants').returning(['id']).insert({
        //id: new_tenant_id,
        name: tname.substring(0, 80),
        encrypt_public_key: tenant.encrypt_public_key
      })

      await tb.table('tenant_account_joins').insert({
        //id: new_tenant_joins_id,
        tenant_id: nt.id,
        account_id: account_id,
        role: 'owner'
      })

      if (args.copyModels) {
        //暂时不支持，但是如果要支持，则需要：复制providers providers_credentials，要构造新的数据。
        //复制tenant_default_models
      }

      return nt.id

    })

    if (!r.ok) {
      console.error(r.error, r.message)
    } else {
      console.log('创建成功(tenant created)')
      console.log(`In Dify Directory, run command(在Dify目录，运行命令): \n  cd docker/volumes/app/storage/privkeys\n  cp -R ${tenant.id} ${r.result}`)
    }

  } else if (arg.command === 'delete') { 
    if (!args.force) {
      console.error('请使用 --force 选项来强制删除')
      return db.end()
    }

    if (!args.id) {
      console.error('请指定要删除的租户ID')
      return db.end()
    }

    let tenant = await db.model('tenants').where({id: args.id}).get()

    if (!tenant) {
      console.error('没有找到ID为' + args.id + '的租户')
      return db.end()
    }

    /**
     * 要删除的数据包括：tenants,tenant_account_joins,providers,providers_credentials,tenant_default_models,upload_files,apps,workflows,workflow_runs,messages,message_files
     * 之后通过命令彻底删除storage的upload_files中的tenant 目录即可
     */

    let r = await db.transaction(async (tb, ret) => { 
      let applist = await tb.table('apps').where({tenant_id: args.id}).select()

      let appids = applist.map(app => app.id)

      if (applist.length > 0) {
        let messages = await tb.table('messages').where({app_id: appids}).returning('id').delete()
        let messageids = messages.map(message => message.id)
        await tb.table('message_files').where({message_id: messageids}).delete()
      }

      await tb.table('tenants').where({id: args.id}).delete()
      await tb.table('tenant_account_joins').where({tenant_id: args.id}).delete()
      await tb.table('providers').where({tenant_id: args.id}).delete()
      await tb.table('provider_credentials').where({tenant_id: args.id}).delete()
      await tb.table('tenant_default_models').where({tenant_id: args.id}).delete()
      await tb.table('upload_files').where({tenant_id: args.id}).delete()
      await tb.table('apps').where({tenant_id: args.id}).delete()
      await tb.table('workflows').where({tenant_id: args.id}).delete()
      await tb.table('workflow_runs').where({tenant_id: args.id}).delete()
    })

    if (!r.ok) {
      console.error(r.error, r.message)
    } else {
      console.log('删除成功(tenant deleted)')
      console.log(`In Dify Directory, run command(在Dify目录，运行命令): \n  cd docker/volumes/app/storage/upload_files\n  if [ -d "${args.id}" ] ; then rm -rf ${args.id}; fi`)
    }
    
  }

  db.end()
})()
